<template>
    <!-- 附件信息 -->
    <div class="e-table table">
        <div class="top">
            <div class="left">
                <div>
                    <el-button
                        size="small"
                        type="primary"
                        plain
                        @click="aptitudeClickAdd"
                        >添加</el-button
                    >
                    <el-button
                        size="small"
                        type="primary"
                        plain
                        @click="handleBatchDownload"
                        v-if="isBatch"
                        >批量下载</el-button
                    >
                    <el-button
                        size="small"
                        type="primary"
                        plain
                        @click="handleBatchDelete"
                        v-if="isBatch"
                        >批量删除</el-button
                    >
                </div>
                <div class="batchBox" @click="batchOperation">
                    <img class="batchicon" src="@/assets/piliang.png" />
                    <span class="batchfont">{{ batch }}</span>
                </div>
            </div>
            <div class="right" v-if="!isTableRowClass">
                <div class="squarecolor">
                    <div class="color colorAdd"></div>
                    <span>新增</span>
                </div>
                <div class="squarecolor item">
                    <div class="color colorUpdate"></div>
                    <span>修改</span>
                </div>
                <div class="squarecolor">
                    <div class="color colorDel"></div>
                    <span>删除/过期</span>
                </div>
            </div>
        </div>
        <div style="margin-bottom:20px" class="errorMsg" v-if="errorMsg.length > 0">
            <span
                style="display: block"
                v-for="(item, index) in errorMsg"
                :key="index"
            >
                {{ item }}
            </span>
        </div>
        <el-table
            class="table"
            :data="aptitudeTable"
            border
            style="width: 100%"
            :max-height="$store.state.tableHeight"
            @selection-change="handleDetailSelectionChange"
            @cell-click="cellClick"
            :row-class-name="tableRowClass"
            ref="table"
            v-sortTable="{ 'tableData': aptitudeTable, '_this': this, 'ref': 'table' }"
        >
            <el-table-column
                type="selection"
                width="55"
                v-if="isBatch"
            ></el-table-column>
            <el-table-column label="序号" type="index" width="60">
            </el-table-column>
            <el-table-column fixed label="操作" width="120">
                <template slot-scope="{ row, $index }">
                    <div class="handle">
                        <div>
                            <el-upload
                                class="upload-demo"
                                style="margin: 7px 5px 0px 0px"
                                :action="uploadUrl"
                                :data="{
                                    bucketName,
                                    relationId,
                                    relationTag: row.fileTypeValue,
                                    orgCode,
                                    index: $index
                                }"
                                :before-upload="beforeAvatarUpload"
                                :accept="accept"
                                :on-success="attachOnSuccess"
                                :http-request="uploadBefore"
                                :show-file-list="false"
                                name="files"
                            >
                                <img src="@/assets/btn/commit.png" />
                            </el-upload>
                        </div>
                       <img
                            v-if="row.id"
                            src="@/assets/btn/downLoad.png"
                            @click="handleDownload(row)"
                             style="margin-right: 5px"
                        />
                        <div>
                            <img
                                v-if="row.changeType != -1"
                                src="@/assets/btn/delete.png"
                                @click="handleDelete(row, $index)"
                            />
                            <img
                                v-else
                                src="@/assets/btn/cancelDelete.png"
                                @click="revoke($index)"
                            />
                            <img
                                style="margin-left: 10px"
                                src="@/assets/btn/preview.png"
                                @click="preview($index)"
                            />
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="类型" width="230">
                <template slot-scope="{ row, $index }">
                    <el-select
                        v-model="row.fileTypeValue"
                        @change="getFileTypes(row, row.fileTypeValue, $index)"
                        placeholder="请选择"
                    >
                        <el-option
                            v-for="item in fileType"
                            :key="item.kvId"
                            :label="item.kvKey"
                            :value="item.kvValue"
                        >
                        </el-option>
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column
                min-width="200"
                show-overflow-tooltip
                prop="fileName"
                label="文件名称"
            >
            </el-table-column>
            <el-table-column prop="fileSize" label="文件大小(KB)" width="150">
                <template slot-scope="{ row }">
                    {{ row.fileSize ? bytesToSize(row.fileSize) : '' }}
                </template>
            </el-table-column>
            <el-table-column prop="gmtCreate" width="150" label="上传时间">
            </el-table-column>
            <el-table-column prop="fileUploaderName" width="150" label="上传人">
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import ossRequest from '@/api/oss/oss.js'
import { bytesToSize, showLoading, hideLoading, getUuid, showErrorPop } from '@/utils/common'
import service from '@/utils/request'
//import ComPagination from '@/components/pagination/pagination'
import call from '@/api/OutsourcingartyAdmin/getAllType.js'
// 编辑附件接口
import { getEnclosureList } from '@/api/OutsourcingartyAdmin/subcontractorAdmin/subcontractor.js'
// 变更接口
import subcontractorChange from '@/api/OutsourcingartyAdmin/subcontractorAdmin/subcontractorChange.js'

export default {
    props: {
        bucketName: {
            type: String,
            default: '',
            require: true
        },
        billId: {
            type: String,
            default: '',
            require: true
        },
        // 是否需要修改样式
        isTableRowClass: {
            type: Boolean,
            default: false
        },
        // 分包商类型
        subcontractorTypeValue: {
            type: Array,
            default: () => {
                return []
            }
        },
        // 是否为境外单位
        isAbroadUnit: {
            type: [String, Number],
            default: ''
        },
        // 是否通过验证
        isSend: {
            type: Boolean,
            default: false
        }
    },
    data () {
        return {
            isBatch: false, //是否进入批量操作
            batch: '进入批量管理',
            checkedDetail: [], //选中的数据
            //上传的地址
            uploadUrl: '/oss/uploader',
            accept: '.jpg,jpeg,.png,.pdf',
            relationId: this.billId, //关联id【单据id】
            relationIdTag: '', //关联id【类型id】
            pagination: {
                limit: 10, //	每页显示条数
                name: '', //合同名称
                orgName: '', //机构
                page: 1 //当前页数
            },
            totalPage: 0, //总页数
            rowIndex: '',
            fileType: [],
            errorMsg: [], //验证数组
            isFrequency: true, //控制初始化数据方法只会执行一次
            aptitudeTable: [], //表单数据
            uplodIndex: '', //上传的index
            oldDate: [], //列表查回来的基础数据
        }
    },
    async created () {
        //获取类型
        call.getCredential('附件类型').then(res => {
            this.fileType = res
            if (this.isFrequency) {
                this.isFrequency = false
            }
        })
        // 初始化列表
        this.getEnclosureList(this.billId)
    },
    computed: {
        orgCode () {
            return this.$store.state.userInfo.orgInfo.shortCode
        }
    },
    methods: {
        //修改行样式
        tableRowClass ({ row }) {
            if (this.isTableRowClass) {
                return
            } else {
                if (row.state == -1) {
                    return 'red'
                } else if (row.state == 1) {
                    return 'green'
                } else if (row.state == 2) {
                    return 'yellow'
                }
                return ''
            }
        },
        // 修改样式
        modifyState (row) {
            this.oldDate.map(item => {
                if (item.id == row.id && row.relationId) {
                    // if( !this.isObjectValueEqual(item, row)) {
                    this.aptitudeTable.map(items => {
                        if (items.id == row.id) {
                            return (items.state = 2)
                        }
                    })
                    // }
                }
            })
        },
        // 初始化列表
        async getEnclosureList (billId) {
            if (this.isTableRowClass) {
                let data = await getEnclosureList({ id: billId })
                if (data != null && data.length > 0) {
                    this.aptitudeTable = data
                }
            } else {
                let data = await subcontractorChange.getEnclosureChangeList(
                    billId
                )
                if (data != null && data.length > 0) {
                    this.aptitudeTable = data
                    this.oldDate = JSON.parse(
                        JSON.stringify(this.aptitudeTable)
                    )
                }
            }
        },
        //选择附件类型的事件
        getFileTypes (row, fileTypeValue, $index) {
            this.modifyState(row)
            const obj = this.fileType.find(
                item => item.kvValue === fileTypeValue
            )
            this.aptitudeTable[$index].fileTypeKey = obj.kvKey
            this.aptitudeTable[$index].relationTag = obj.kvValue
        },
        //是否批量管理
        batchOperation () {
            this.isBatch = !this.isBatch
            if (this.isBatch) {
                this.batch = '退出批量管理'
                this.$refs.table.clearSelection()
            } else {
                this.batch = '进入批量管理'
            }
        },
        cellClick (row) {
            //是第几行
            this.rowIndex = this.aptitudeTable.findIndex(x => x === row)
        },
        aptitudeAddRow () {
            let oldEnclosureId = this.fileType.map(item => {
                return item.kvKey
            })
            let oldEnclosureName = this.fileType.map(item => {
                return item.kvValue
            })
            if (
                this.subcontractorTypeValue.includes('8') ||
                (this.subcontractorTypeValue.includes('9') &&
                    this.isAbroadUnit == 0)
            ) {
                for (var i in oldEnclosureId) {
                    let obj = {
                        billId: '',
                        changeType: 1,
                        downloadQty: null,
                        fileName: '',
                        filePath: '',
                        fileSize: null,
                        fileTypeDictName: '',
                        fileTypeKey: oldEnclosureId[i], //附件类型
                        fileTypeValue: oldEnclosureName[i], //附件类型
                        fileUploaderId: '',
                        fileUploaderName: '',
                        gmtCreate: '',
                        gmtModified: '',
                        id: '',
                        objectSource: '',
                        ossId: '',
                        relationId: this.billId, //关联id1
                        relationTag: oldEnclosureName[i], //关联id2
                        sourceId: '',
                        state: 1,
                        uuid: getUuid(), //本地的uuid区分每条数据
                        newState: '1', //当期新增字段，判断是当前次新增的数据还是从后端请求回来的数据
                        dialogImage: '' //图片预览
                    }
                    this.aptitudeTable.push(obj)
                }
            }
        },
        // 点击添加一行
        aptitudeClickAdd () {
            let obj = {
                billId: '',
                changeType: 1,
                downloadQty: null,
                fileName: '',
                filePath: '',
                fileSize: null,
                fileTypeDictName: '',
                fileTypeKey: '', //附件类型
                fileTypeValue: '', //附件类型
                fileUploaderId: '',
                fileUploaderName: '',
                gmtCreate: '',
                gmtModified: '',
                id: '',
                objectSource: '',
                ossId: '',
                relationId: this.billId, //关联id1
                relationTag: '', //关联id2
                sourceId: '',
                state: 1,
                uuid: getUuid(), //本地的uuid区分每条数据
                newState: '1', //当期新增字段，判断是当前次新增的数据还是从后端请求回来的数据
                dialogImage: '' //图片预览
            }
            this.aptitudeTable.push(obj)
        },
        //选中的行
        handleDetailSelectionChange (selection) {
            this.checkedDetail = selection
        },
        //删除一行
        handleDelete (row, $index) {
            if (this.isTableRowClass) {
                this.clientPop(
                    'info',
                    this.oneDeleteErr,
                    this.callback(row, $index)
                )
            } else {
                this.clientPop(
                    'info',
                    this.oneDeleteErr,
                    this.callbacks(row, $index)
                )
            }
        },
        // 编辑删除回调
        callback (row, index) {
            return () => {
                if(row.id) {
                    let data = []
                    row.changeType = -1
                    data.push(row)
                    this.$emit('getAttachData', data)
                }else{
                    this.aptitudeTable.splice(index, 1)
                }

            }
        },
        // 变更删除回调
        callbacks (row, index) {
            return () => {
                if (!row.newState) {
                    this.aptitudeTable[index].changeType = -1
                    this.aptitudeTable[index].state = -1
                } else {
                    this.aptitudeTable.splice(index, 1)
                }
            }
        },
        // 撤销
        revoke (index) {
            this.aptitudeTable[index].changeType = 0
            this.aptitudeTable[index].state = 1
        },
        //批量删除
        handleBatchDelete () {
            const length = this.checkedDetail.length
            this.clientPop(
                'info',
                `已选择【${length}】条数据，确定要删除吗？`,
                this.delete
            )
        },
        delete () {
            let num = 0
            this.checkedDetail.filter(item => {
                // 如果有id ，则改changeType为-1
                if (item.recordId) {
                    num++
                    ossRequest.deleterRecordId({ recordId: item.recordId })
                } else {
                    num++
                    // 如果没有id，判断uuid是否相同，相同则在原数据删除
                    this.aptitudeTable.map((items, index) => {
                        if (item.uuid == items.uuid) {
                            this.aptitudeTable.splice(index, 1)
                        }
                    })
                }
            })
            if (num == this.checkedDetail.length) {
                this.getObjectByRelationId()
            }
        },
        //下载某一行
        async handleDownload (obj) {
            showLoading()
            const url = obj.objectPath
            const fileNameFull = obj.objectName
            const fileExt = fileNameFull.split('.').pop()
            if (
                ['jpg', 'jpeg', 'gif', 'png', 'bmp'].indexOf(
                    fileExt.toLowerCase()
                ) === -1
            ) {
                const { httpGetFile } = service
                const data = await httpGetFile({ url })
                const blob = new Blob([data])
                const reader = new FileReader()
                reader.readAsDataURL(blob)
                reader.onload = function (e) {
                    this.autoClick({
                        fileName: fileNameFull,
                        url: e.target.result
                    })
                }.bind(this)
            } else {
                this.downloadIamge(url, fileNameFull)
            }
            hideLoading()
        },
        downloadIamge (imgsrc, fileName) {
        //下载图片地址和图片名
            var image = new Image()
            // 解决跨域 Canvas 污染问题
            image.setAttribute('crossOrigin', 'anonymous')
            image.onload = function () {
                const canvas = document.createElement('canvas')
                canvas.width = image.width
                canvas.height = image.height
                const context = canvas.getContext('2d')
                context.drawImage(image, 0, 0, image.width, image.height)
                const _dataURL = canvas.toDataURL('image/png') //得到图片的base64编码数据

                const blob_ = this.dataURLtoBlob(_dataURL) // 用到Blob是因为图片文件过大时，在一部风浏览器上会下载失败，而Blob就不会

                const url = {
                    name: fileName || '图片.png', // 图片名称不需要加.png后缀名
                    src: blob_
                }

                if (window.navigator.msSaveOrOpenBlob) {
                // if browser is IE
                    navigator.msSaveBlob(url.src, url.name) //filename文件名包括扩展名，下载路径为浏览器默认路径
                } else {
                    this.autoClick({
                        fileName: url.name,
                        url: window.URL.createObjectURL(url.src)
                    })
                }
            }.bind(this)
            image.src = imgsrc
        },
        dataURLtoBlob (dataurl) {
            var arr = dataurl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = window.atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new Blob([u8arr], { type: mime })
        },
        autoClick ({ fileName, url }) {
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = url
            document.body.appendChild(elink)
            elink.click()
            document.body.removeChild(elink)
        },
        //批量下载
        handleBatchDownload () {},
        //文件大小
        beforeAvatarUpload (file) {
            const isLt2M = file.size / 1024 / 1024 < 20

            if (!isLt2M) {
                this.clientPop('err', '上传文件大小不能超过 20MB！')
            }
            return isLt2M
        },
        //上传成功
        attachOnSuccess () {
            this.getObjectByRelationId()
        },
        //获取上传成功的对象
        getObjectByRelationId () {
            if (!this.relationId) return
            return ossRequest
                .getObjectByRelationId({ relationId: this.relationId })
                .then(res => {
                    if (res.length > 0) {
                        res.map(item => {
                            item.fileName = item.objectName
                            item.fileSize = item.objectSize
                            item.fileTypeValue = item.relationIdTag
                            item.fileUploaderName = item.ossBucketName
                        })
                        this.aptitudeTable = res
                    } else {
                        // 当res无数据的时候，先把 this.aptitudeTable置空再调用方法
                        this.aptitudeTable = []
                        this.aptitudeAddRow()
                    }
                })
        },

        bytesToSize (byte) {
            return bytesToSize(byte)
        },
        //覆盖默认的上传行为，可以自定义上传的实现
        uploadBefore (params) {
            this.uplodIndex = params.data.index
            if (params.data.relationTag) {
                params.data.relationId = this.billId
                // params.data.relationIdTag = this.billId
                let obj = {
                    ...params.data,
                    files: params.file
                }
                this.$Ajax
                    .httpPostForm({
                        url: this.uploadUrl,
                        params: obj
                    })
                    .then(res => {
                        res.map(x => {
                            x.fileName = x.objectName
                            x.fileSize = x.objectSize
                            x.fileTypeValue = x.relationIdTag
                            x.fileUploaderName = x.ossBucketName
                            return scrollX
                        })
                        this.$set(
                            this.aptitudeTable[this.rowIndex],
                            'dialogImage',
                            res[0].objectPath
                        )
                        this.$set(
                            this.aptitudeTable[this.uplodIndex],
                            'fileName',
                            res[0].objectName
                        )
                        this.$set(
                            this.aptitudeTable[this.uplodIndex],
                            'recordId',
                            res[0].recordId
                        )
                        this.$set(
                            this.aptitudeTable[this.uplodIndex],
                            'fileSize',
                            res[0].objectSize
                        )
                        this.$set(
                            this.aptitudeTable[this.uplodIndex],
                            'fileUploaderName',
                            res[0].ossBucketName
                        )
                        this.$set(
                            this.aptitudeTable[this.uplodIndex],
                            'fileTypeValue',
                            res[0].relationIdTag
                        )
                        this.$set(
                            this.aptitudeTable[this.uplodIndex],
                            'relationId',
                            this.relationId
                        )
                        this.$set(
                            this.aptitudeTable[this.uplodIndex],
                            'gmtCreate',
                            res[0].gmtCreate.slice(
                                0,
                                res[0].gmtCreate.indexOf(' ')
                            )
                        )
                        this.modifyState(this.aptitudeTable[this.uplodIndex])
                    })
            } else {
                this.$emit('setError', 'accessory')
                showErrorPop('请先选择类型')
            }
        },
        // 验证方法
        preserve () {
            this.errorMsg = []
            let oldArry = ['0', '1', '2', '3', '4']
            if (
                (this.subcontractorTypeValue.includes('8') ||
                this.subcontractorTypeValue.includes('9')) &&
                    this.isAbroadUnit == 0
            ) {
                /**
                 * 1当外包方类型选择含有“施工分包”、“劳务合作”中的1个或2个且没有勾选“是否为境外单位”的时候，默认上面9个类型行，其中，承诺书、组织机构图、上年度财务报告或企业年报、国家企业信用信息截图、社保证明5类必须上传附件，其他类不必传
                 */
                let isEnclosure = [] //定义人员类型临时数组
                // 将类型存入临时数组
                isEnclosure = this.aptitudeTable.map(item => {
                    if(item.state != -1) {
                        return item.fileTypeValue
                    }
                })
                // 去重
                let isEnclosures = [...new Set(isEnclosure)]
                // 检验哪些不包含在该数组
                let newData = []
                newData = oldArry.filter(item => {
                    if (!isEnclosures.includes(item)) {
                        return item
                    }
                })
                //判断人员类型是否包含5种类型，不包含则提示
                if (newData.length > 0) {
                    this.fileType.forEach(item => {
                        if (newData.includes(item.kvValue)) {
                            this.$emit('setError', 'accessory')
                            this.$emit('update:isSend', false)
                            this.errorMsg.push(
                                '请添加' + `${item.kvKey.split(',')}`
                            )
                        }
                    })
                } else {
                    // 验证通过修改状态
                    let isStr = false
                    this.aptitudeTable.forEach((item, index) => {
                        let str1 = `请上传第 ${index + 1} 行的`
                        if (
                            item.fileTypeKey === '' ||
                            item.fileTypeKey === null
                        ) {
                            let str = '类型,'
                            isStr = true
                            str1 += str
                        }
                        if (item.fileName === '' || item.fileName === null) {
                            let str = '文件,'
                            isStr = true
                            str1 += str
                        }
                        if (isStr) {
                            this.errorMsg.push(str1)
                        }
                    })
                    if (this.errorMsg.length > 0) {
                        this.$emit('update:isSend', false)
                        this.$emit('setError', 'accessory')
                        return
                    } else {
                        // 将值传回父组件
                        this.$emit('update:isSend', true)
                        this.$emit('update:attachTable', this.aptitudeTable)
                    }
                }
            } else {
                //境外单位无验证，直接将值传回父组件
                this.$emit('update:isSend', true)
                this.$emit('update:attachTable', this.aptitudeTable)
            }
        },
        //预览附件
        preview (val) {
            if (this.aptitudeTable[val].dialogImage) {
                window.open(this.aptitudeTable[val].dialogImage)
            } else {
                this.clientPop('err', '请先上传附件')
            }
        }
    },
}
</script>

<style lang="scss" scoped>
.handle {
    display: flex;
    align-items: center;
    text-align: left;
    div {
        cursor: pointer;
    }
    .download {
        font-size: 23px;
        font-weight: bold;
        color: rgb(122, 168, 24);
    }
}
</style>
